package com.hui.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/07/09/8:54
 * @Description: 判断是否已登入
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("loginFilter初始化成功！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Cookie[] cookies = req.getCookies();
        boolean flag = false;
        if(null!=cookies){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name")) {
                    flag = true;
                    break;
                }
            }
        }
        if (flag) {
            // 如果存在用户名，就放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 不存在用户名，就转发到登入页面
            req.getRequestDispatcher("index.jsp").forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("loginConfig已销毁！");
    }
}
